package com.taomu.app.zongchouhuli.moudle.home.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.bumptech.glide.Glide;
import com.taomu.app.zongchouhuli.R;
import com.taomu.app.zongchouhuli.entity.BaseChangeResponse;
import com.taomu.app.zongchouhuli.entity.BaseFinishEntity;
import com.taomu.app.zongchouhuli.framework.BaseActivity;
import com.taomu.app.zongchouhuli.framework.CommonWebActivity;
import com.taomu.app.zongchouhuli.http.res.ResMainProductListEntity;
import com.taomu.app.zongchouhuli.http.res.ResProductDetailEntity;
import com.taomu.app.zongchouhuli.http.res.ResProductDetailInfoEntity;
import com.taomu.app.zongchouhuli.http.res.ResProductEntity;
import com.taomu.app.zongchouhuli.http.res.ResUserInfoEntity;
import com.taomu.app.zongchouhuli.moudle.home.adpter.HomeProductHisAdp;
import com.taomu.app.zongchouhuli.moudle.home.adpter.HomeProductSpecialAdp;
import com.taomu.app.zongchouhuli.moudle.home.contract.HomeProductDetailContract;
import com.taomu.app.zongchouhuli.moudle.home.contract.impl.HomeProductDetailPresenter;
import com.taomu.app.zongchouhuli.moudle.home.entity.ProductHistEntity;
import com.taomu.app.zongchouhuli.moudle.index.adpter.BaseProductAdp;
import com.taomu.app.zongchouhuli.moudle.index.entity.ProductEntity;
import com.taomu.app.zongchouhuli.moudle.login.activity.LoginActivity;
import com.taomu.app.zongchouhuli.utils.ParseUtil;
import com.taomu.app.zongchouhuli.utils.RxBus2;
import com.taomu.app.zongchouhuli.utils.StorageHelper;
import com.taomu.app.zongchouhuli.utils.TimeUtils;
import com.taomu.app.zongchouhuli.utils.dialog.OrderDialog;
import com.taomu.app.zongchouhuli.utils.dialog.SelectBalanceTypeDialog;
import com.taomu.app.zongchouhuli.utils.dialog.SelectQQDialog;
import com.taomu.app.zongchouhuli.utils.entity.OrderExplainEntity;
import com.taomu.app.zongchouhuli.utils.entity.OrderNumEntity;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class HomeProductDetailActivity extends BaseActivity<HomeProductDetailContract.Presenter> implements HomeProductDetailContract.View{

    private ImageView mBackIm;

    //剩余产品数量
    private TextView mSurplusTv;

    //截止购买时间
    private TextView mEndTimeTv;

    //结算规则
    private TextView mSettleRuleTv;

    //标题栏产品名称
    private TextView mTitleNameTv;

    private ImageView mShareIm;

    //产品价格，中间
    private TextView mPriceTv;

    //收益率
    private TextView mIncomeRaidoTv;

    //产品名称，中间
    private TextView mProductNameTv;

    //产品特色
    private RecyclerView mSpecialRecy;

    private HomeProductSpecialAdp mSpecialAdp;

    //产品购买历史
    //private RecyclerView mHistoryRecy;

    private HomeProductHisAdp mHisAdp;

    //更多推荐
    private RecyclerView mProductRecy;

    private BaseProductAdp mProductAdp;

    //产品价格，底部
    private TextView mProductPriceTv;

    //结算方式，收益率
    private TextView mBalanceTypeTv;

    //立即购买
    private TextView mSubmitTv;

    private TextView mSpectailTv;

    private OrderDialog mOrderDialog;

    private ImageView mBgIm;

    private LinearLayout mHistLin;

    public static final String PRODUCTTYPEID = "productId";

    public static final String DISTRIBUTIONID = "userid";

    private String distribution_id = "";

    private ScrollView mScrollView;

    private WebView mWebView;

    private ViewFlipper mViewFlipper;

    public static void start(Context mContext,String _id){
        Intent intent = new Intent(mContext,HomeProductDetailActivity.class);
        intent.putExtra(PRODUCTTYPEID, _id);
        mContext.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        mPresenter.detch();
        super.onDestroy();
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_home_product_detail;
    }

    @Override
    protected void initView() {
        mScrollView = findViewById(R.id.scrollView);
        mViewFlipper = findViewById(R.id.product_detail_viewflipper);
        mHistLin = findViewById(R.id.product_detail_his_lin);
        mBackIm = findViewById(R.id.home_productdetail_back_im);
        mTitleNameTv = findViewById(R.id.home_productdetail_name_tv);
        mBgIm = findViewById(R.id.home_productdetail_icon_im);
        mShareIm = findViewById(R.id.home_productdetail_share_im);
        mSurplusTv = findViewById(R.id.home_productdetail_num_tv);
        mEndTimeTv = findViewById(R.id.home_productdetail_time_tv);
        mSettleRuleTv = findViewById(R.id.home_productdetail_rule_tv);
        mPriceTv = findViewById(R.id.home_productdetail_product_price_tv);
        mIncomeRaidoTv = findViewById(R.id.home_productdetail_income_radio_tv);
        mProductNameTv = findViewById(R.id.home_productdetail_product_name_tv);
        mSpectailTv = findViewById(R.id.home_productdetail_specail_tv);
        mSpecialAdp = new HomeProductSpecialAdp(this);
        mSpecialRecy = findViewById(R.id.home_productdetail_specail_recy);
        mSpecialRecy.setLayoutManager(new LinearLayoutManager(this));
        mSpecialRecy.setNestedScrollingEnabled(false);
        mSpecialRecy.setAdapter(mSpecialAdp);
//        mHisAdp = new HomeProductHisAdp(this);
//        mHistoryRecy = findViewById(R.id.home_productdetail_history_recy);
//        mHistoryRecy.setNestedScrollingEnabled(false);
//        mHistoryRecy.setLayoutManager(new LinearLayoutManager(this));
//        mHistoryRecy.setAdapter(mHisAdp);
        mProductAdp = new BaseProductAdp(this);
        mProductRecy = findViewById(R.id.home_productdetail_more_recy);
        //防止上传srollview+recycleview 自动滑到最顶部
        mProductRecy.setFocusableInTouchMode(false);
        mProductRecy.requestFocus();
        mProductRecy.setNestedScrollingEnabled(false);
        mProductRecy.setLayoutManager(new LinearLayoutManager(this));
        mProductRecy.setAdapter(mProductAdp);
        mProductPriceTv = findViewById(R.id.home_productdetail_price_tv);
        mBalanceTypeTv = findViewById(R.id.home_productdetail_balance_type_tv);
        mSubmitTv = findViewById(R.id.home_productdetail_submit_tv);
        mWebView = findViewById(R.id.web_view);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        mWebView.getSettings().setLoadWithOverviewMode(true);
    }

    private String productId = "-1";

    @Override
    protected void initData() {
        if(getIntent() != null){
            distribution_id = getIntent().getStringExtra(DISTRIBUTIONID);
            productId = getIntent().getStringExtra(PRODUCTTYPEID);
            if(getIntent().getData() != null){
                Uri uri = getIntent().getData();
                if(!TextUtils.isEmpty(uri.getQueryParameter(PRODUCTTYPEID))) {
                    productId = uri.getQueryParameter(PRODUCTTYPEID);//获取传递参数
                }
                if(!TextUtils.isEmpty(uri.getQueryParameter(DISTRIBUTIONID))) {
                    distribution_id = uri.getQueryParameter(DISTRIBUTIONID);
                }
            }
            mPresenter.getBaseProductInfo(productId);
            mPresenter.getProductRecommond();

        }
        mPresenter.getBuyHistListData();
        mPresenter.getProductListData();
        mPresenter.getSpecialListData();
        initBaseData();
    }

    @Override
    protected void initEvent() {
        mBackIm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mSubmitTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(StorageHelper.isLogin()) {
                    showBaseDialog();
                }else{
                    Intent intent = new Intent(HomeProductDetailActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            }
        });
        mProductAdp.setProductAdpListener(new BaseProductAdp.ProductAdpListener() {
            @Override
            public void onItemClick(ResMainProductListEntity.DataBean entity) {
                HomeProductDetailActivity.start(HomeProductDetailActivity.this,String.valueOf(entity.getId()));
                finish();
            }
        });
        mShareIm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(StorageHelper.isLogin()){
//                    http://39.98.83.102/api/index/shareUrl?productId=1&userId=21820510
                    String content = "http://39.98.83.102/api/index/shareUrl?productId="+productId+"&userId="+ParseUtil.parseObject(StorageHelper.getAccountInfo(), ResUserInfoEntity.class).getId();
                    share(content);
                }else{
                    Intent intent = new Intent(HomeProductDetailActivity.this, LoginActivity.class);
                    startActivity(intent);
                }

            }
        });
        RxBus2.getInstance().toObservable(BaseFinishEntity.class)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseFinishEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseFinishEntity baseFinishEntity) {
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected HomeProductDetailContract.Presenter createPresenter() {
        return new HomeProductDetailPresenter(this);
    }

    @Override
    public void setSpecialListData(List<String> mData) {
        mSpecialAdp.setData(mData);
    }

    @Override
    public void setBuyHistListData(List<ProductHistEntity> mData) {

    }

    @Override
    public void setProductListData(List<ProductEntity> mData) {
        //mProductAdp.setData(mData);
    }

    private Handler handler = new Handler();


    private String totalNum = "10";

    private String price = "0.00";

    private String product_img = "";

    private int leftNum = 0;

    @Override
    public void setBaseInfo(BaseChangeResponse<ResProductDetailInfoEntity> mData) {
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                mScrollView.post(new Runnable() {
//                    @Override
//                        public void run() {
//                            // TODO Auto-generated method stub
//                            mScrollView.fullScroll(ScrollView.FOCUS_UP);
//                    }
//                });
//            }
//        }, 500);
        if(!TextUtils.isEmpty(mData.getData().getInfo().getProduct_desc())) {
            if (mData.getData().getInfo().getProduct_desc().contains("<img")) {
                mSpectailTv.setVisibility(View.GONE);
                //mSpectailTv.setText(Html.fromHtml(mData.getData().getInfo().getProduct_desc(),imgGetter,null));
                mWebView.loadDataWithBaseURL(null, mData.getData().getInfo().getProduct_desc(), "text/html", "utf-8", null);
            } else {
                mSpectailTv.setVisibility(View.VISIBLE);
                mSpectailTv.setText(Html.fromHtml(mData.getData().getInfo().getProduct_desc(), imgGetter, null));
//            mWebView.loadDataWithBaseURL (null, mData.getData().getInfo().getProduct_desc(), "text/html", "utf-8", null);
                mWebView.setVisibility(View.GONE);
            }
        }
        if(mData.getData() != null) {
            if(mData.getData().getBuyList().size() != 0) {
                mViewFlipper.removeAllViews();
                for (int i = 0; i < mData.getData().getBuyList().size(); i++) {
                    View view = LayoutInflater.from(this).inflate(R.layout.item_product_detail_history, null);
                    TextView textView = view.findViewById(R.id.item_product_detail_his_content_tv);
                    textView.setText(mData.getData().getBuyList().get(i).getUsername());
                    TextView time = view.findViewById(R.id.item_product_detail_his_time_tv);
                    if(mData.getData().getBuyList().get(i).getComplete_date() != 0) {
                        time.setText(TimeUtils.timeFomart(mData.getData().getBuyList().get(i).getComplete_date()));
                    }
                    mViewFlipper.addView(view);
                }
                mViewFlipper.startFlipping();
//                mHisAdp.setData(mData.getData().getBuyList());
                mHistLin.setVisibility(View.VISIBLE);
            }else{
                mHistLin.setVisibility(View.GONE);
            }
        }else{
            mHistLin.setVisibility(View.GONE);
        }
        mExplainEntities.clear();
        mBanlanceTypeEntities.clear();
        price = mData.getData().getInfo().getProduct_price();
        totalNum = String.valueOf(mData.getData().getInfo().getLimit_num());
        mBalanceTypeTv.setText("日结"+String.valueOf(mData.getData().getInfo().getDay_income())+"%");
        OrderExplainEntity entity1 = new OrderExplainEntity();
        entity1.setTypeName("日结");
        entity1.setTypeid("1");
        entity1.setRadioName(String.valueOf(mData.getData().getInfo().getDay_income())+"%");
        mExplainEntities.add(entity1);
        mBanlanceTypeEntities.add(entity1);
        mSelectBanlanceTypeEntity = entity1;
        mSelectExplainEntity = entity1;
        OrderExplainEntity entity2 = new OrderExplainEntity();
        entity2.setTypeName("周结");
        entity2.setTypeid("2");
        entity2.setRadioName(String.valueOf(mData.getData().getInfo().getWeek_income())+"%");
        mExplainEntities.add(entity2);
        mBanlanceTypeEntities.add(entity2);
        OrderExplainEntity entity3 = new OrderExplainEntity();
        entity3.setTypeName("月结");
        entity3.setTypeid("3");
        entity3.setRadioName(String.valueOf(mData.getData().getInfo().getMonth_income())+"%");
        mExplainEntities.add(entity3);
        mBanlanceTypeEntities.add(entity3);
        mTitleNameTv.setText(mData.getData().getInfo().getProduct_name());
        mProductNameTv.setText(mData.getData().getInfo().getProduct_name());
        if("0".equals(mData.getData().getInfo().getProduct_limit_num())) {
            mSurplusTv.setVisibility(View.GONE);
        }else{
            mSurplusTv.setVisibility(View.GONE);
            mSurplusTv.setText("限购"+String.valueOf(mData.getData().getInfo().getProduct_limit_num())+"件");
        }
        //todo:product_lock_num
        mEndTimeTv.setText(TimeUtils.timeFomartOnlyDate(mData.getData().getInfo().getEnd_date()) + "截止");
        mPriceTv.setText("¥"+mData.getData().getInfo().getProduct_price());
        mIncomeRaidoTv.setText(mData.getData().getInfo().getDay_income());
        mProductPriceTv.setText("¥"+mData.getData().getInfo().getProduct_price());
        iconImg = mData.getData().getInfo().getProduct_img_uri();
        Glide.with(this).load(mData.getData().getInfo().getProduct_img_uri()).into(mBgIm);
        product_img = mData.getData().getInfo().getProduct_img_uri();
        leftNum = mData.getData().getInfo().getProduct_left_num();
    }

    private String iconImg = "";

    @Override
    public void setRecommond(ResMainProductListEntity resProductEntities) {
        mProductAdp.setData(resProductEntities.getData());
    }

    @Override
    public void setShareUrl(String url) {
        share(url);
    }

    private List<OrderExplainEntity> mExplainEntities;

    private OrderExplainEntity mSelectExplainEntity;

    private List<OrderExplainEntity> mBanlanceTypeEntities;

    private OrderExplainEntity mSelectBanlanceTypeEntity;

    private List<OrderNumEntity> mNumEntities;

    private OrderNumEntity mSelectNumEntity;

    private String[] types = {"日结","周结","月结"};

    private String[] radios = {"2%","3.5%","5%"};

    private String[] nums = {"1","3","5","10"};

    private void initBaseData(){
        //设置默认滚动到顶部

        this.mExplainEntities = new ArrayList<>();
        this.mBanlanceTypeEntities = new ArrayList<>();
        this.mNumEntities = new ArrayList<>();
        for(int i=0;i<3;i++){
            OrderExplainEntity entity = new OrderExplainEntity();
            entity.setRadioName(radios[i]);
            entity.setTypeName(types[i]);
            entity.setTypeid(String.valueOf(i));
            if(i == 0){
                this.mSelectBanlanceTypeEntity = entity;
                this.mSelectExplainEntity = entity;
            }
            mExplainEntities.add(entity);
            mBanlanceTypeEntities.add(entity);
        }
        for(int i=0;i<nums.length;i++){
            OrderNumEntity entity = new OrderNumEntity();
            entity.setOrderNum(nums[i]);
            entity.setContent(nums[i]+"件");
            if(i == 0){
                this.mSelectNumEntity = entity;
            }
            this.mNumEntities.add(entity);
        }
    }

    private void showBaseDialog(){
        if(mOrderDialog == null){
            mOrderDialog = new OrderDialog();
            mOrderDialog.setBaseData(mBanlanceTypeEntities,mSelectBanlanceTypeEntity,mExplainEntities,mSelectExplainEntity,mNumEntities,mSelectNumEntity);
            //todo:这里改用product_limit_num
            mOrderDialog.setLimitNum(totalNum);
            mOrderDialog.setPrice(price);
            mOrderDialog.setImage(product_img);
            mOrderDialog.setOrderDialogListener(new OrderDialog.OrderDialogListener() {
                @Override
                public void onConfirmClick(OrderExplainEntity mType, OrderExplainEntity mExplain, OrderNumEntity mNumEntity) {
                    String type = "";
                    double money = 0;
                    String pice = ParseUtil.parseObject(StorageHelper.getAccountInfo(), ResUserInfoEntity.class).getAccount();
                    double priceaccount = 0;
                    if(!TextUtils.isEmpty(pice)) {
                        priceaccount = Double.valueOf(pice);
                    }
                    if(!TextUtils.isEmpty(price)){
                        money = Double.valueOf(price)*Integer.valueOf(mNumEntity.getOrderNum());
                    }
                    if("日结".equals(mExplain.getTypeName())){
                        type = "day_income";
                    }else if("周结".equals(mExplain.getTypeName())){
                        type = "week_income";
                    }else if("月结".equals(mExplain.getTypeName())){
                        type = "month_income";
                    }
                    if(Integer.valueOf(mNumEntity.getOrderNum())>leftNum){
                        showToast("商品剩余不足");
                    }else if(money>priceaccount){
                        showToast("账户余额不足");
                    }else {
                        HomeOrderSubmitActivity.start(HomeProductDetailActivity.this, productId, mNumEntity.getOrderNum(), type, mTitleNameTv.getText().toString(), mExplain.getRadioName(), price, distribution_id, iconImg);
                    }
                }

                @Override
                public void setSelectBalanceInfo(OrderExplainEntity mType, OrderExplainEntity mExplain, OrderNumEntity mNumEntity) {
                    mBalanceTypeTv.setText(mType.getTypeName()+mType.getRadioName());
                    mSelectBanlanceTypeEntity = mType;
                    mSelectExplainEntity = mExplain;
                    mSelectNumEntity = mNumEntity;
                }
            });
            mOrderDialog.show(getSupportFragmentManager(),"baseselect");
        }else{
            mOrderDialog.setBaseData(mBanlanceTypeEntities,mSelectBanlanceTypeEntity,mExplainEntities,mSelectExplainEntity,mNumEntities,mSelectNumEntity);
            mOrderDialog.show(getSupportFragmentManager(),"baseselect");
        }
    }

    @Override
    public void setPresenter(HomeProductDetailContract.Presenter presenter) {

    }

    private SelectQQDialog qqdialog;

    private void share(final String content){
        Intent share_intent = new Intent();
        //share_intent.setComponent(comp);
        share_intent.setAction(Intent.ACTION_SEND);//设置分享行为
        share_intent.setType("text/plain");//设置分享内容的类型
        share_intent.putExtra(Intent.EXTRA_SUBJECT, "分享");//添加分享内容标题
        if(StorageHelper.isLogin()) {
            share_intent.putExtra(Intent.EXTRA_TEXT, content);//添加分享内容
        }
        //创建分享的Dialog
        share_intent = Intent.createChooser(share_intent, "分享");
        startActivity(share_intent);
//        if(qqdialog == null) {
//            qqdialog = new SelectQQDialog();
//            qqdialog.setSelectShareListener(new SelectQQDialog.SelectShareListener() {
//                @Override
//                public void onItemClick(String type) {
//                    if("wx".equals(type)){
//                        shareWx(content);
//                    }else{
//                        shareQQ(content);
//                    }
//                }
//            });
//        }
//        qqdialog.show(getSupportFragmentManager(), "qq");
    }

    private void shareWx(String content){
        ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
        Intent share_intent = new Intent();
        share_intent.setComponent(comp);
        share_intent.setAction(Intent.ACTION_SEND);//设置分享行为
        share_intent.setType("text/plain");//设置分享内容的类型
        share_intent.putExtra(Intent.EXTRA_SUBJECT, "分享");//添加分享内容标题
        if(StorageHelper.isLogin()) {
            share_intent.putExtra(Intent.EXTRA_TEXT, content);//添加分享内容
        }
        //创建分享的Dialog
        share_intent = Intent.createChooser(share_intent, "分享");
        startActivity(share_intent);
    }

    private void shareQQ(String content){
        ComponentName comp = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
        Intent share_intent = new Intent();
        share_intent.setComponent(comp);
        share_intent.setAction(Intent.ACTION_SEND);//设置分享行为
        share_intent.setType("text/plain");//设置分享内容的类型
        share_intent.putExtra(Intent.EXTRA_SUBJECT, "分享");//添加分享内容标题
        if(StorageHelper.isLogin()) {
            share_intent.putExtra(Intent.EXTRA_TEXT, content);//添加分享内容
        }
        //创建分享的Dialog
        share_intent = Intent.createChooser(share_intent, "分享");
        startActivity(share_intent);
    }

    //这里面的resource就是fromhtml函数的第一个参数里面的含有的url
    Html.ImageGetter imgGetter = new Html.ImageGetter() {
        public Drawable getDrawable(String source) {
            Log.i("RG", "source---?>>>" + source);
            Drawable drawable = null;
            URL url;
            try {
                url = new URL(source);
                Log.i("RG", "url---?>>>" + url);
                drawable = Drawable.createFromStream(url.openStream(), ""); // 获取网路图片
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            Log.i("RG", "url---?>>>" + url);
            return drawable;
        }
    };
}
